package com.hanyxx.thread;

import lombok.SneakyThrows;

/**
 * synchronized会锁住整个对象中被synchronized修饰的方法。
 * 运行结果：methodOne方法执行，2秒后，methodTwo方法执行
 * @author layman
 * @date 2021/2/5
 */
public class Demo06 {
    public static void main(String[] args) {
        Demo06Service service = new Demo06Service();
        Demo06ThreadA threadA = new Demo06ThreadA(service);
        Demo06ThreadB threadB = new Demo06ThreadB(service);
        threadA.start();
        threadB.start();
    }
}
class Demo06Service{
    @SneakyThrows
    public synchronized void methodOne(){
        System.out.println("methodOne方法执行");
        Thread.sleep(2000);
    }
    @SneakyThrows
    public synchronized void methodTwo(){
        System.out.println("methodTwo方法执行");
        Thread.sleep(2000);
    }
}
class Demo06ThreadA extends Thread{
    private Demo06Service service;
    public Demo06ThreadA(Demo06Service service){
        this.service = service;
    }
    @Override
    public void run() {
        service.methodOne();
    }
}class Demo06ThreadB extends Thread{
    private Demo06Service service;
    public Demo06ThreadB(Demo06Service service){
        this.service = service;
    }
    @Override
    public void run() {
        service.methodTwo();
    }
}
